import axios, { type AxiosRequestHeaders, type AxiosResponse } from 'axios';
import { ElMessage } from 'element-plus';
import pinia from '@/stores/index';
import {useUserInfoStore} from '@/stores/userInfo'

interface ResponseData<T> {
	code: number;
	data: T;
	message: string;
}


// 配置新建一个 axios 实例
const service = axios.create({
	baseURL: import.meta.env.VITE_API_URL, //'/app-dev' / /app-prod
	timeout: 50000,
});


service.interceptors.request.use(
	(config) => {
		let token = useUserInfoStore(pinia).token
		if(token){
			(config.headers as AxiosRequestHeaders).token = token
		}
		return config // 必须要返回 
	}
);



service.interceptors.response.use(
	// 先获取到后端返回的data
	async (reponse:AxiosResponse<ResponseData<any>>) => {
		const res = reponse.data
		if(res.code !== 20000 && res.code !== 200){
			ElMessage({
				message: (typeof res.data=='string' && res.data) || res.message || 'Error',
				type: 'error',
				duration: 5 * 1000
			})
			return Promise.reject(service.interceptors.response)
		} else {
			return res.data   //成功的话把后台给的成功数据获取
		}
	},
	(error) => {
		ElMessage.error('发送ajax请求失败' + error.message) //统一处理错误
		return Promise.reject(error);
	}
);

export default service


